package me.zxk.smartagriculture.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import me.zxk.smartagriculture.common.ApiResponse;
import me.zxk.smartagriculture.dto.greenhouse.*;
import me.zxk.smartagriculture.service.GreenhouseService;
import me.zxk.smartagriculture.util.JwtUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 大棚控制器
 */
@Tag(name = "大棚管理", description = "大棚信息管理、传感器数据查询等API")
@RestController
@RequestMapping("/api/greenhouses")
@RequiredArgsConstructor
@SecurityRequirement(name = "bearerAuth")
public class GreenhouseController {

    private final GreenhouseService greenhouseService;
    private final JwtUtil jwtUtil;

    /**
     * 创建大棚
     */
    @Operation(summary = "创建大棚", description = "创建新的大棚信息，包括名称、位置、种植作物等基本信息")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "大棚创建成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "400",
                    description = "创建失败，参数错误或数据验证失败",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @PostMapping
    public ApiResponse<GreenhouseDetailResponse> createGreenhouse(
            @Parameter(description = "大棚创建请求信息", required = true) @Valid @RequestBody CreateGreenhouseRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            GreenhouseDetailResponse response = greenhouseService.createGreenhouse(userId, request);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 获取大棚列表
     */
    @Operation(summary = "获取大棚列表", description = "分页查询当前用户的大棚列表，支持排序")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "查询成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "500",
                    description = "服务器内部错误",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @GetMapping
    public ApiResponse<Page<GreenhouseListResponse>> getGreenhouseList(
            @Parameter(description = "页码，从0开始", example = "0") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "排序字段和方向，格式：字段名,方向(asc/desc)", example = "createdAt,desc") @RequestParam(defaultValue = "createdAt,desc") String sort,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);

            // 解析排序参数
            String[] sortParams = sort.split(",");
            String sortField = sortParams[0];
            Sort.Direction direction = sortParams.length > 1 && "asc".equalsIgnoreCase(sortParams[1])
                    ? Sort.Direction.ASC : Sort.Direction.DESC;

            Pageable pageable = PageRequest.of(page, size, Sort.by(direction, sortField));
            Page<GreenhouseListResponse> response = greenhouseService.getGreenhouseList(userId, pageable);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 获取大棚详情
     */
    @Operation(summary = "获取大棚详情", description = "根据大棚ID获取大棚的详细信息")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "查询成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "404",
                    description = "大棚不存在或无权限访问",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @GetMapping("/{greenhouseId}")
    public ApiResponse<GreenhouseDetailResponse> getGreenhouseDetail(
            @Parameter(description = "大棚ID", required = true, example = "1") @PathVariable Long greenhouseId,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            GreenhouseDetailResponse response = greenhouseService.getGreenhouseDetail(userId, greenhouseId);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error(404, e.getMessage());
        }
    }

    /**
     * 更新大棚信息
     */
    @Operation(summary = "更新大棚信息", description = "更新指定大棚的基本信息，如名称、位置、种植作物等")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "更新成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "400",
                    description = "更新失败，参数错误或数据验证失败",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @PutMapping("/{greenhouseId}")
    public ApiResponse<GreenhouseDetailResponse> updateGreenhouse(
            @Parameter(description = "大棚ID", required = true, example = "1") @PathVariable Long greenhouseId,
            @Parameter(description = "大棚更新请求信息", required = true) @Valid @RequestBody UpdateGreenhouseRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            GreenhouseDetailResponse response = greenhouseService.updateGreenhouse(userId, greenhouseId, request);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 删除大棚
     */
    @Operation(summary = "删除大棚", description = "删除指定的大棚及其相关数据")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "删除成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "404",
                    description = "大棚不存在或无权限访问",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @DeleteMapping("/{greenhouseId}")
    public ApiResponse<Void> deleteGreenhouse(
            @Parameter(description = "大棚ID", required = true, example = "1") @PathVariable Long greenhouseId,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            greenhouseService.deleteGreenhouse(userId, greenhouseId);
            return ApiResponse.success("大棚删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error(404, e.getMessage());
        }
    }

    /**
     * 获取大棚最新传感器数据
     */
    @Operation(summary = "获取大棚最新传感器数据", description = "获取指定大棚的最新传感器数据")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "查询成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "500",
                    description = "服务器内部错误",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @GetMapping("/{greenhouseId}/sensor-data")
    public ApiResponse<SensorDataResponse> getSensorData(
            @Parameter(description = "大棚ID", required = true, example = "1") @PathVariable Long greenhouseId,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            SensorDataResponse response = greenhouseService.getSensorData(userId, greenhouseId);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 获取大棚所有传感器数据
     */
    @Operation(summary = "获取大棚所有传感器数据", description = "分页查询指定大棚的所有传感器数据，支持时间范围筛选")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "查询成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "500",
                    description = "服务器内部错误",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @GetMapping("/{greenhouseId}/sensor-data/all")
    public ApiResponse<Page<SensorDataResponse>> getAllSensorData(
            @Parameter(description = "大棚ID", required = true, example = "1") @PathVariable Long greenhouseId,
            @Parameter(description = "开始时间，ISO格式", example = "2024-01-01T00:00:00") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @Parameter(description = "结束时间，ISO格式", example = "2024-01-31T23:59:59") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
            @Parameter(description = "页码，从0开始", example = "0") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "recordedAt"));
            Page<SensorDataResponse> response = greenhouseService.getAllSensorData(
                    userId, greenhouseId, startTime, endTime, pageable);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String token = extractTokenFromRequest(request);
        return jwtUtil.getUserIdFromToken(token);
    }

    /**
     * 从请求中提取JWT Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        throw new RuntimeException("Token not found");
    }
}
